﻿global using System.Collections.ObjectModel;
using DocumentMakingTools.Models;
using DocumentMakingTools.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DocumentMakingTools.ViewModels
{
    internal class HomeViewModel
    {
        Page page;
        public Command PickSourceFilesCommand { get; set; }
        public Command MakeDocumentCommand { get; set; }
        public Command SourceFileTappedCommand { get; set; }
        public ObservableCollection<SourceFileModel> SourceFiles { get; set; }
        public HomeViewModel(Page page)
        {
            this.page = page;

            SourceFiles = new ObservableCollection<SourceFileModel>();

            PickSourceFilesCommand = new Command(ExecutePickSourceFilesCommand);
            MakeDocumentCommand = new Command(ExecuteMakeDocumentCommand);
            SourceFileTappedCommand = new Command((object obj) => ExecuteSourceFileTappedCommand(obj));
        }
        async void ExecutePickSourceFilesCommand()
        {
            var fileResults = await FileService.PickFiles();
            fileResults.ForEach(async (result) =>
            {
                var stream = await result.OpenReadAsync();
                var sourceFile = new SourceFileModel
                {

                    FileName = result.FileName,
                    FilePath = result.FullPath,
                    FileSize = stream.Length
                };
                SourceFiles.Add(sourceFile);
            });
        }
        async void ExecuteMakeDocumentCommand()
        {
            try
            {
                var softname = await page.DisplayPromptAsync("软件名称", "注意以\"软件\"\"系统\"等字样结尾，且含有版本号", "确定", "取消");
                var company = await page.DisplayPromptAsync("公司名称", "如是个人请输入著作权人姓名", "确定", "取消");

                await Task.Factory.StartNew(() => 
                {
                    var path = Path.Combine(App.AppSetting.DefaultOutputPath, $"程序-{softname}.docx");
                    if (File.Exists(path)) File.Delete(path);
                    var service = new WordDocumentService(path);

                    // 同步方法，源代码有序，但性能较差
                    foreach (var item in SourceFiles)
                    {
                        var encoding = Encoding.UTF8;
                        // 部分IDE对cpp文件按照gbk编码
                        if (Path.GetExtension(item.FileName)[1..] == "cs") encoding = Encoding.GetEncoding("GB2312");

                        using var reader = new StreamReader(item.FilePath, encoding);
                        var line = "";

                        while ((line = reader.ReadLine()) is not null)
                        {
                            if (!string.IsNullOrEmpty(line))
                            {
                                while (line.StartsWith(' '))
                                    line = line.TrimStart(' ');
                                while (line.StartsWith('\t'))
                                    line = line.TrimStart('\t');
                                service.AppendText(line);
                            }
                        }
                    }

                    //// 异步多线程，提高速度，但生成文档中源代码乱序
                    //SourceFiles.ToList().AsParallel().ForAll((item) =>
                    //{
                    //    using var reader = new StreamReader(item.FilePath, encoding: Encoding.GetEncoding("GB2312"));
                    //    var line = "";

                    //    while ((line = reader.ReadLine()) != null)
                    //    {
                    //        if (!string.IsNullOrEmpty(line))
                    //        {
                    //            while (line.StartsWith(' '))
                    //                line = line.TrimStart(' ');
                    //            while (line.StartsWith('\t'))
                    //                line = line.TrimStart('\t');
                    //            service.AppendText(line);
                    //        }
                    //    }
                    //});

                    service.Save(softname, company);
                    service.Dispose();

                    if (App.AppSetting.DefaultOpenCodeDocumentMode) 
                        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(path) { UseShellExecute = true });
                });
            }
            catch (Exception)
            {
                await page.DisplayAlert("错误", "指定输出路径有同名文档且无法覆盖,或无访问权限", "确定");
            }

        }
        async void ExecuteSourceFileTappedCommand(object obj)
        {
            var sourceFile = obj as SourceFileModel;
            var action = await page.DisplayActionSheet($"你要对{sourceFile.FileName}做什么", "取消", null, "删除", "编辑");
            switch (action)
            {
                case "删除":
                    SourceFiles.Remove(sourceFile);
                    break;
                case "编辑":
                    System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(sourceFile.FilePath) { UseShellExecute = true});
                    break;
                default: break;
            }
        }
    }
}
